// Thread.h
#pragma once
#include <pthread.h>
#include <unistd.h>
#include "Semaphore.h"
#include "Nocopyable.h"

class Thread : private Nocopyable {
public:
    Thread() : m_Thread(0) {}
    virtual ~Thread() {}

    bool Activate() {
        if (pthread_create(&m_Thread, NULL, Thread::Function, this) == 0) {
            m_Sem.Wait(); // 等待线程启动
            return true;
        }
        return false;
    }

    virtual void Stop() {
        if (m_Thread != 0) {
            pthread_cancel(m_Thread);
            m_Thread = 0;
        }
    }

    void Join() {
        if (m_Thread != 0) {
            pthread_join(m_Thread, NULL);
            m_Thread = 0;
        }
    }

    static void Sleep(int msecs) {
        usleep(msecs * 1000);
    }

protected:
    virtual void Run() = 0;

private:
    static void* Function(void* arg) {
        Thread* pThread = static_cast<Thread*>(arg);
        pThread->m_Sem.Post(); // 通知主线程：已启动
        pThread->Run();
        return NULL;
    }

    pthread_t m_Thread;
    Semaphore m_Sem;
};
